package com.chitang.operation;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.chitang.pool.ChannelHandlePool;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: wjs
 * @CreateTime: 2023-03-10 15:42
 * websocket操作类
 */
@Component
public class WebsocketOperation {

    private ConcurrentHashMap<String, Channel> getChannelMap() {
        ConcurrentHashMap<String, Channel> channelMap = ChannelHandlePool.channelMap;
        return channelMap;
    }

    /**
     * 单发消息
     *
     * @param userId
     * @param msg
     */
    public void send(String userId, String msg) {
        ConcurrentHashMap<String, Channel> channelMap = getChannelMap();
        if (MapUtil.isNotEmpty(channelMap)) {
            if (channelMap.containsKey(userId)) {
                Channel channel = channelMap.get(userId);
                channel.writeAndFlush(new TextWebSocketFrame(msg));
            }
        }
    }

    /**
     * 群发消息
     *
     * @param msg
     */
    public void sendAll(String msg) {
        ConcurrentHashMap<String, Channel> channelMap = getChannelMap();
        if (MapUtil.isNotEmpty(channelMap)) {
            for (Map.Entry<String, Channel> channelEntry : channelMap.entrySet()) {
                channelEntry.getValue().writeAndFlush(new TextWebSocketFrame(msg));
            }
        }
    }
}
